package pipe

import (
	"gitee.com/injoyai/goutil/bytes/coding/json"
	"gitee.com/injoyai/goutil/g"
)

type Message struct {
	Key  string `json:"key"`  //标识
	Data string `json:"data"` //内容
	Type Type   `json:"type"` //类型 通道进行的操作
	Addr string `json:"addr"` //目标地址
}

func (this *Message) String() string {
	return string(this.Bytes())
}

func (this *Message) Bytes() []byte {
	bs, _ := json.Marshal(this)
	return bs
}

func (this *Message) Close(data string) *Message {
	return newCloseMsg(this.Key, data)
}

func decodeMsg(bytes []byte) (*Message, error) {
	m := new(Message)
	err := json.Unmarshal(bytes, m)
	if err != nil {
		return nil, err
	}
	bs, err := g.DecodeBase64(m.Data)
	if err != nil {
		return nil, err
	}
	m.Data = string(bs)
	return m, nil
}

func newCloseMsg(key, data string) *Message {
	return &Message{
		Key:  key,
		Type: Close,
		Data: g.EncodeBase64([]byte(data)),
	}
}

func newConnectMsg(key, addr string) *Message {
	return &Message{
		Key:  key,
		Addr: addr,
		Type: Connect,
	}
}

func newWriteMsg(key, addr string, data string) *Message {
	return &Message{
		Key:  key,
		Addr: addr,
		Type: Write,
		Data: g.EncodeBase64([]byte(data)),
	}
}

func newInfoMsg(key string, data []byte) *Message {
	return &Message{
		Key:  key,
		Type: Info,
		Data: g.EncodeBase64(data),
	}
}

func newRegisterMsg(key, data string) *Message {
	return &Message{
		Key:  key,
		Type: Register,
		Data: g.EncodeBase64([]byte(data)),
	}
}
